package main

//现在的难点主要是理解那个channel是干什么的，
//目前我的理解其功能类似是一个连接的manager
//我认为每一个连接都要有一个ch，
//ch是不能被其他包给调用的（换言之每一个连接的ch是独立的）

import (
	"fmt"
	"github.com/streadway/amqp"
	"log"
)

func failOnError(err error, msg string) {
	if err != nil {
		log.Fatalf("%s: %s", msg, err)
		panic(fmt.Sprintf("%s: %s", msg, err))
	}
}

func main() {
	conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
	failOnError(err, "Failed to connect to RabbitMQ")
	defer conn.Close()

	ch, err := conn.Channel()
	failOnError(err, "Failed to open a channel")
	defer ch.Close()

	err = ch.ExchangeDeclare(
		"los",    // name
		"fanout", // type
		true,     // durable
		false,    // auto-deleted
		false,    // internal
		false,    // no-wait
		nil,      // arguments
	)

	failOnError(err, "Failed to declare an exchange")

	//func (ch *Channel) QueueDeclare(name string, durable,
	//autoDelete, exclusive, noWait bool, args Table)
	q, err := ch.QueueDeclare(
		"test",
		true,
		false,
		false,
		false,
		nil,
	)
	failOnError(err, "ch.QueueDeclare err!")
	//name, key, exchange string, noWait bool, args Table

	err = ch.QueueBind( //给指定队列绑了一个exchange
		q.Name,
		"",
		"los",
		false,
		nil,
	)
	failOnError(err, "ch.QueueBin err")
	//queue, consumer string, autoAck, exclusive, noLocal, noWait bool,
	//args Table
	msgs, err := ch.Consume(
		q.Name,
		"",
		true,
		false,
		false,
		false,
		nil,
	)
	failOnError(err, "ch.Consume err !")
	forever := make(chan bool)

	go func() {
		for d := range msgs {
			log.Printf(" [x] %s", d.Body)
		}
	}()

	log.Printf(" [*] Waiting for logs. To exit press CTRL+C")
	<-forever
}
